app.controller('TaskListController', ['$scope', 'tasks', function ($scope, tasks) {
    $scope.listtask; 
    $scope.mode;
    $scope.Submitted=false;
    $scope.entity ;
    //load list
    tasks.getList().then(function(result){
    	  $scope.listtask = result;
    	  
      });
    
    $scope.CreateNew=function(){
    	 $scope.entity = {
    	    		"nm_tax":'',
    	            "ds_tax":'',
    	            "vl_tax_amount":0.0            
    	    }
    	 $scope.mode="New";
    	 //$scope.$apply();
    }
    
    $scope.Save=function(isvalid)
    {
    	$scope.Submitted=true;
    	if(isvalid)
    		{
    		if($scope.mode ==="New")
    			{
    		//go to insert	
    			tasks.insert($scope.entity).then(function(result){
    					
    					$scope.listtask = result;
    				});
    			}
    		else
    			{
    			//goto update
    			tasks.edit($scope.entity).then(function(result){
					
    				$scope.listtask = result;
				});
    			}
    		
    		}
    }
    initTable();
    //inital column and binding list catelog to table.
    function initTable() {

        $scope.aoColumns = [
        { "sTitle": "Name" },
        { "sTitle": "Description" }, 
		{ "sTitle": "Tax Amount" },           
        {
            "sTitle": "",
            "mRender": function (obj) {
              
                var action = "<a href=\"\" onclick=\"angular.element(this).scope().Edit('" + obj + "')\">" +
                                "<i class=\"fa fa-edit\"></i>" +
                            "</a>" +
                            "<a href=\"\" onclick=\"angular.element(this).scope().Delete('" + obj + "')\"><i class=\"fa fa-ban\"></i></a>";

                return action;
            }
        }];

        $scope.aoColumnDefs = [
                            { "mDataProp": "nm_tax", "aTargets": [0] },
                            { "mDataProp": "ds_tax", "aTargets": [1] },
                            { "mDataProp": "vl_tax_amount", "aTargets": [2] }, 
                            { "mDataProp": "id", "aTargets": [3] }
        ];
    }
    //edit entity
    $scope.Edit = function (id)
    {
        var u = $.grep($scope.listtask, function (e) { return e.id == id; });
        var entity = u[0];
        if (entity != undefined) {
            $scope.entity = entity;
            $scope.mode ="Update";
            $scope.$apply();
        }
    }

    //delete entity
    $scope.Delete = function (id)
    {
        var u = $.grep($scope.listtask, function (e) { return e.id == id; });
        var entity = u[0];
        if (entity != undefined) {
            if (confirm("Are you sure you want to delete this item?")) {
                tasks.del(entity).then(function (result) {
                	 $scope.listtask = result;
                })
            }
        }
    }
}]);

